package com.fh.shop.admin.controller.user;

import com.fh.shop.admin.annotation.LogInfo;
import com.fh.shop.admin.biz.user.IUserService;
import com.fh.shop.admin.common.DataTableResult;
import com.fh.shop.admin.common.ServerResponse;
import com.fh.shop.admin.common.SystemContant;
import com.fh.shop.admin.controller.FilePathController;
import com.fh.shop.admin.po.user.User;
import com.fh.shop.admin.common.ResponseEnum;
import com.fh.shop.admin.param.user.*;
import com.fh.shop.admin.util.FileUtil;
import com.fh.shop.admin.util.Md5Util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController extends FilePathController {

    @Resource(name = "userService")
    private IUserService userService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "user/add";
    }

    @RequestMapping("/toList")
    public String toList(){
        return "user/list";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(){
        return "user/update";
    }

    /**
     * 修改密码
     */
    @GetMapping("/updatePwd")
    public @ResponseBody
    ServerResponse updatePwd(UserPasswordParam userPasswordParam){
        //获取session中的值
        User user = (User) request.getSession().getAttribute(SystemContant.CURR_USER);
        //放入userPasswordParam中
        userPasswordParam.setUser(user);
        return userService.updatePwd(userPasswordParam);
    }


    /**
     * 注销
     */
    @GetMapping("/logout")
    @LogInfo(info = "登出系统")
    public String logout(){
        //清空session
        request.getSession().invalidate();
        //重定向到登录页面
        return "redirect:"+SystemContant.LOGIN_PAGE;
    }

    /**
     * 登录拦截
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @LogInfo(info = "登入系统")
    public @ResponseBody ServerResponse login(LoginParam loginParam){
        String userName = loginParam.getUserName();
        String password = loginParam.getPassword();
        //非空验证
        //取反编程思想
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
            return ServerResponse.error(ResponseEnum.USERNAME_PASSWORD_IS_NULL);
        }
        //判断用户名是否正确
        //首先获取用户的信息
        User user = userService.findUserByUserName(userName);
        if (user == null){
            return ServerResponse.error(ResponseEnum.USERNAME_ERROR);
        }
        //判断密码是否正确
        // 把用户输入的密码加盐加密再和数据库对比
        if (!Md5Util.md5(password).equals(user.getUserPassword())){
            return ServerResponse.error(ResponseEnum.PASSWORD_ERROR);
        }
        //否则登录成功，将用户信息放入到session中，方便后续操作调用
        request.getSession().setAttribute(SystemContant.CURR_USER,user);
        return ServerResponse.success();
    }

    /**
     * 增加功能
     * @param userAddParam
     * @return
     */
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ResponseBody
    @LogInfo(info = "用户增加")
    public ServerResponse addUser(@RequestBody UserAddParam userAddParam){
        return userService.addUser(userAddParam);
    }

    /**
     * 列表展示
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public @ResponseBody
    DataTableResult list(UserQueryParam userQueryParam){
        logger.info("控制层——用户列表展示");
        return userService.findList(userQueryParam);
    }

    /**
     * 回显
     */
    @RequestMapping(value = "/findUserById",method = RequestMethod.GET)
    public @ResponseBody ServerResponse findUserById(Long id){
        return userService.findUserById(id);
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @LogInfo(info = "用户修改")
    public @ResponseBody ServerResponse updateUser(@RequestBody UserUpdateParam userUpdateParam){
        String realPath = getRealPath(request, "/");
        return userService.updateUser(userUpdateParam,realPath);
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @LogInfo(info = "用户删除")
    public @ResponseBody ServerResponse deleteUser(Long id){
        return userService.deleteUser(id,getRealPath(request,"/"));
    }

    /**
     * 批量删除
     */
    @RequestMapping(value = "/deleteBatch",method = RequestMethod.POST)
    @LogInfo(info = "用户批量删除")
    public @ResponseBody ServerResponse deleteBatch(String ids){
        return userService.deleteBatch(ids,getRealPath(request,"/"));
    }

    /**
     * 导出Word
     */
    @RequestMapping(value = "exportWord",method = RequestMethod.GET)
    @ResponseBody
    public void exportWord(Long userId){
        //查询用户数据
        Map<String,Object> res = userService.findUser(userId);
        Configuration configuration = new Configuration();
        //设置编码
        configuration.setDefaultEncoding("utf-8");
        //获取文件夹位置
        configuration.setClassForTemplateLoading(this.getClass(),"/templates");
        //获取文件全路径
        String fileName = "d:/xuexi/"+UUID.randomUUID().toString()+".docx";

        FileOutputStream fileOutputStream = null;
        OutputStreamWriter out = null;
        try {
            //获取模板
            Template template = configuration.getTemplate("jianli2.xml");
            //指定服务器文件夹
            fileOutputStream = new FileOutputStream(fileName);
            //输出流
            out = new OutputStreamWriter(fileOutputStream, "utf-8");
            //模板和数据融合上传到服务器硬盘中
            template.process(res,out);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关流
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
        //根据文件路径找到文件名
        File file = new File(fileName);

        //下载文件
        FileUtil.downloadFile(request,response,file);

        //删除文件
        if (file.exists()){
            file.delete();
        }

    }
}
